package mysql;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;

public class Connector {
        private Logger logger = LoggerFactory.getLogger(Connector.class);
        private  String driver = "com.mysql.jdbc.Driver";
        private  String url = null;
        private  String user = null;
        private  String password = null;
        private  Connection conn = null;

        public Connector(String url, String user, String password) {
            this.url = url;
            this.user = user;
            this.password = password;
        }


        Connection getConn() throws Exception{
            try {
                if(checkResult()) {
                    logger.error("url, user, password均不能为空");
                    return null;
                }
                if(conn != null) {
                    return conn;
                }
                // 加载驱动程序
                Class.forName(driver);
                // 连续数据库
                conn = DriverManager.getConnection(url, user, password);
                return conn;
            } catch (Exception e) {
                logger.error("获取数据库连接异常" + e.getMessage(), e);
                return null;
            }
        }



        public void closeConnection() throws Exception{
            if(!conn.isClosed()) {
                conn.close();
            }
        }

        private boolean checkResult() {
            if(StringUtils.isBlank(url) ||
                    StringUtils.isBlank(user)||
                    StringUtils.isBlank(password)) {
                return true;
            }
            return false;
        }
}
